using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using E4RPTools;
using Movements.DataSet;

namespace Movements.Controls
{
    public partial class TargetEntityXtraForm : XtraForm
    {
        private long _documentId;
        private Controller _controller;
        private EntidadeDestinoDataSet _dataSet;

        #region Properties

        public long DocumentId
        {
            set { _documentId = value; }
        }

        public Controller Controller
        {
            set { _controller = value; }
        }

        #endregion

        public TargetEntityXtraForm()
        {
            InitializeComponent();
            Load += TargetEntityXtraFormLoad;
            OKSimpleButton.Click += OKSimpleButtonClick;
        }

        #region Private Methods

        private void MergeData()
        {
            _dataSet = new EntidadeDestinoDataSet();
            if (_documentId <= 0)
            {
                var targetEntity = _dataSet.EntidadeDestino.NewEntidadeDestinoRow();
                targetEntity.Id = _documentId;
                targetEntity.Nome = "";
                _dataSet.EntidadeDestino.AddEntidadeDestinoRow(targetEntity);
            }
            else
                _dataSet.Merge(_controller.GetTargetEntity(_documentId));
        }

        private void SetDataToControls()
        {
            nameTextEdit.Text = _dataSet.EntidadeDestino[0].Nome;            
        }

        private void GetDataFromControls()
        {
            _dataSet.EntidadeDestino[0].Nome = nameTextEdit.Text;            
        }

        private void ClearControlErrors()
        {
            dxErrorProvider.SetError(nameTextEdit, "");            
        }

        private Control GetControl(string reference)
        {
            switch (reference)
            {
                case "Nome":
                    return nameTextEdit;
                default:
                    return null;
            }
        }

        private void SetControlErrors(Result result)
        {
            foreach (var error in result.Errors)
                dxErrorProvider.SetError(GetControl(error.Reference), error.Message);
        }

        #endregion

        void TargetEntityXtraFormLoad(object sender, EventArgs e)
        {
            MergeData();
            SetDataToControls();
        }

        void OKSimpleButtonClick(object sender, EventArgs e)
        {
            ClearControlErrors();
            GetDataFromControls();
            var result = _controller.IsTargetEntityValid(_dataSet);
            if (result.Failed)
            {
                DialogResult = DialogResult.None;
                SetControlErrors(result);
            }
            else
                _controller.SaveTargetEntity(_dataSet);
        }
    }
}